﻿using System;
using System.Runtime.InteropServices;
using System.Net;

namespace AccessControl.Video.Rtp
{
	class RtcpPacketHeader
	{
		public byte Version { get; set; }
		public byte Padding { get; set; }
		public byte Count { get; set; }
		public byte Type { get; set; }
		public ushort Length { get; set; }

		public void FromBytes(byte[] aBytes)
		{
			Version = (byte)(aBytes[0] >> 6);
			Padding = (byte)(aBytes[0] & 0x20);
			Count = (byte)(aBytes[0] & 0x1F);
			Type = aBytes[1];
			Length = (ushort)BitConverter.ToInt16(aBytes, 2);
		}

		public byte[] ToBytes()
		{
			byte[] aBytes = new byte[4];

			aBytes[0] |= (byte)(Version << 6);
			aBytes[0] |= (byte)(Version << 5);
			aBytes[0] |= (byte)(Count);
			aBytes[1] = Type;

			Array.Copy(BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)Length)), 0, aBytes, 2, 2);

			return aBytes;
		}
	}

	class RtcpReceiverReport
	{
		public UInt32 ReporterSSRC { get; set; }
		public UInt32 ReporteeSSRC { get; set; }
		public UInt32 PacketsAndFractionLost { get; set; }
		public UInt32 Extended { get; set; }
		public UInt32 Jitter { get; set; }
		public UInt32 LSR { get; set; }
		public UInt32 DLSR { get; set; }

		public byte[] ToBytes()
		{
			int idx = 0;
			byte[] aBytes = new byte[32];

			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)ReporterSSRC)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)ReporteeSSRC)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)PacketsAndFractionLost)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)Extended)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)Jitter)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)LSR)), 0, aBytes, idx, 4);
			idx += 4;
			Array.Copy(BitConverter.GetBytes((uint)IPAddress.HostToNetworkOrder((int)DLSR)), 0, aBytes, idx, 4);
			idx += 4;

			return aBytes;
		}
	}
}
